package io.polly.interceptor;

import io.polly.annotation.Permission;
import io.polly.secure.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ldz
 * @version V1.0
 * @title: PermissionInterceptor
 * @description: TODO(用一句话描述该文件做什么)
 * @date: 2022/3/28 20:18
 */
@Component
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {

    public static final String DEFAULT_REALM = "Polly";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        // 获取处理method
        if (handler instanceof HandlerMethod == false) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;

        Permission pmn= method.getMethodAnnotation(Permission.class);

        if(pmn==null)
            pmn = method.getBeanType().getAnnotation(Permission.class);
        if(pmn==null)
            return true;

        if (pmn.value().length > 1)
            return true;
        else {

            if(authentication(request,response)){
                 return true;
            }
            else {

                response.setStatus(401);
                response.setHeader("WWW-Authenticate", "Basic Realm=" + DEFAULT_REALM);
                return false;
            }
        }

    }

    private Boolean authentication(HttpServletRequest request, HttpServletResponse response){
        String authorization = request.getHeader("Authorization");

        // 如果不是以 Basic 作为前缀，则视为无效
        if(authorization == null || authorization.startsWith("Basic ") == false) {
            return false;
        }

        String authStr = Base64Util.decode(authorization.substring(6));

        int authIndex = authStr.indexOf(":");
        if(authStr.substring(0,authIndex).equals("my"))
            return true;

        return false;

    }
}
